﻿CREATE PROCEDURE usix.s_DealersExport
	@MinDist tinyint,@MaxDist tinyint
AS
--SET NOCOUNT ON
--DECLARE  SELECT @MinDist = 90,@MaxDist = 80
DECLARE @IDs TABLE(DealerID int, [Dealer Code] varchar(5))

WHILE 1 = 1 BEGIN
	INSERT INTO @IDs SELECT DealerID,[Dealer Code] FROM usix.DealersExport(@MinDist,DEFAULT)

	UPDATE t_Dealer 
	SET UsixID = D_U.[Dealer Code],
		Name = D_U.Name,
		Street = D_U.Address,
		City= D_U.City,
		State = D_U.State,
		Zip = LEFT(D_U.Zipcode,5),
		Phone= D_U.[Phone #], Contact = D_U.Contact, IsIndependent =  CASE NF WHEN 'NF' THEN 1 ELSE 0 END
	FROM t_Dealer D
	INNER JOIN @IDs IDs ON D.ID = IDs.DealerID
	INNER JOIN AFCBANK.DataMining.dbo.v_ALL_Dealers D_U ON IDs.[Dealer Code] = D_U.[Dealer Code]
	SET @MinDist = @MinDist - 1
	PRINT @MinDist
	IF @MinDist < @MaxDist BREAK
	DELETE FROM @IDs
END
